package dao;

import beans.Pizza;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class PizzaDAO extends DAO<Pizza> {

	Connection laCo = null;
	PreparedStatement leStm = null;
	ResultSet result = null;
	
	@Override
	public Pizza create(Pizza obj) {
		try {
			laCo = dataSource.getConnection();
			
			leStm=laCo.prepareStatement("INSERT INTO pizza (NOM, PRIX) VALUES (?, ?)");
			leStm.setString(1, obj.getNom());
			leStm.setFloat(2, obj.getPrix());
			
			leStm.executeUpdate();
			
			leStm.close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if(laCo != null) laCo.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return obj;
	}

	@Override
	public Pizza update(Pizza obv) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void delete(Pizza obv) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Pizza find(long id) {
		Pizza ret = null;
		try {
			laCo = dataSource.getConnection();
			
			leStm=laCo.prepareStatement("SELECT id, nom, prix FROM pizza WHERE id=?");
			leStm.setLong(1, id);
			result = leStm.executeQuery();
		
			if(result.next()) {
				ret = new Pizza(result.getInt(1), result.getString(2), result.getFloat(3));
			}
			
			leStm.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(laCo != null) laCo.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}

	@Override
	public List<Pizza> findAll() {
		List<Pizza> ret = null;
		try {
			laCo = dataSource.getConnection();
			
			leStm=laCo.prepareStatement("SELECT id, nom, prix FROM pizza");
			
			result = leStm.executeQuery();
			
			ret = new ArrayList<Pizza>();
			
			while(result.next()) {
				ret.add(new Pizza(result.getInt(1), result.getString(2), result.getFloat(3)));
			}
			
			leStm.close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if(laCo != null) laCo.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return ret;
	}

}
